package com.bawei.image.glidemodule

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.LibraryGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * Author: Jason Zhang
 * Date: 2024/9/13
 * Desc: 使用OKhttpClient设置网络缓存大小
 */

@GlideModule
class OkHttpModule: LibraryGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //1.创建OKHttpClient的Builder
        val builder = OkHttpClient.Builder()
        //外部SD的目录
        val externalDir = Environment.getExternalStorageDirectory()
        if (externalDir.exists()){
            val cacheDir = "${externalDir.absolutePath}/cacheImages"
            var cacheFile = File(cacheDir)
            if (!cacheFile.exists()){
                cacheFile = File(cacheDir)
            }
            //设置缓存文件对象
            val cache = Cache(cacheFile, 300 * 1024 * 1024L)
            builder.cache(cache)
        } else {
            val cacheDir = "${context.externalCacheDir?.absolutePath}/cacheImages"
            var cacheFile = File(cacheDir)
            if (!cacheFile.exists()){
                cacheFile = File(cacheDir)
            }

            var cacheSize = 50 * 1024 * 1024L
            context.externalCacheDir?.totalSpace?.let {
                cacheSize = it / 8L
            }

            val cache = Cache(cacheFile, cacheSize)
            builder.cache(cache)
        }

        //2.替换OKHttpClient对象
        val newOkHttpClient = builder.build()
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(newOkHttpClient))

    }




}